<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>冒泡排序</title>
</head>

<body>
  <script type="text/javascript">

    /* 冒泡排序的思想：
          让数组中的当前项和后一项进行比较，
          如果当前项比后一项大，则两项交换位置（让大的靠后）即可
    */

    /* 
      bubble: 实现冒泡排序
        @params
          ary [array] 需要排序的数组
        @return
          [array] 排序后的新数组
     */

    function bubble(ary) {
      let temp = null;
      // 外层循环 i 控制比较的论数
      for (let i = 0; i < ary.length - 1; i++) {
        // 里层循环控制每一轮比较的次数 j
        for (let j = 0; j < ary.length - 1 - i; j++) {
          if (ary[j] > ary[j + 1]) {
            // 当前项大于后一项
            temp = ary[j];
            ary[j] = ary[j + 1];
            ary[j + 1] = temp;
          }
        }
      }
      return ary;
    }
    let ary = [12, 8, 24, 16, 1]
    ary = bubble(ary);
    console.log(ary);
  </script>
</body>

</html>